<?php
namespace app\index\controller;

use rongyun\ServerAPI;
use think\Controller;
use think\Db;
use think\Session;
class Chat extends Controller
{
    public function _initialize()
    {
      
        if(empty(Session::get('userid'))||Session::get('member')!="ok"){
            return redirect("/member/");
        }

  //var_dump();
    }

    //聊天主方法
    public function index()
    {
        /*
        注释：引入融云extend，use rongyun\serverapi；
          会员数据库过于庞大，此处在用户信息新建了参与聊天的用户表
         */
        $appKey = config('APP_KEY');
        $appSecret = config('APP_SECRET');

        $rongYun = new ServerAPI( $appKey, $appSecret );

        $data['name']=Session::get('username')?Session::get('username'):"用户ID:".Session::get('userid');
        $data['tx']=Session::get('userimg')?Session::get('userimg'):"http://www.xxxxx.cn/img/all.png";


       if(empty(Session::get('userid'))||Session::get('member')!="ok"){
            return redirect("/member/");
        }
     
        

        $token = $rongYun->getToken(Session::get('userid'),$data['name'],$data['tx']);


    //  var_dump($token);

        $token = json_decode( $token, true )['token'];
        $this->assign([
            'token' => $token,
            'title'=>"xx-实时通讯"
        ]);
        return $this->fetch();
    }

    //所有的用户信息
    public function userInfo()
    {

  //var_dump($targetId,$obj);


           if(empty(Db::table("shuaijin_dcj_user_chat")->where("userid",Session::get('userid'))->find())){
            $data['utime']=time();
            $data['userid']=Session::get('userid');
            $data['name']=Session::get('username')?Session::get('username'):"用户ID:".Session::get('userid');
            $data['tx']=Session::get('userimg')?Session::get('userimg'):"http://www.xxxxx.cn/img/all.png";
          
       

             Db::table("shuaijin_dcj_user_chat")->insert($data);
        }


        $return['userlist'] =Db::table("shuaijin_dcj_user_chat")->cache(true,10)->field("userid as id,name,tx as portraitUri ")->where("userid",input('get.targetId'))->select();

     // var_dump(input('get.'),$return['userlist']);exit();

      /*   [
            ['id' => 1, 'name' => '张三', 'portraitUri' => 'http://www.xxxx.com/static/images/1.jpg'],
            ['id' => 2, 'name' => '李四', 'portraitUri' => 'http://www.xxxxx.com/static/images/2.jpg']
        ];*/
        return json( $return );
    }

    //登录用户信息
    public function onLine()
    {

       
       if(empty(input('get.arr'))){
        return;
       }

        $return['data'] =Db::table("shuaijin_dcj_user_chat")
        ->cache(true,10)
        ->field("userid as id,name,tx as portraitUri ")
        ->where("userid","in",input('get.arr'))
        ->select(); 
 

       /* [
            ['id' => '1', 'status' => true],
            ['id' => '2', 'status' => true]
        ];*/
        return json( $return['data'] );
    }


}
